package com.eques.demo.lock

import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.RadioGroup
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.eques.base.BaseActivity
import com.eques.database.dao.ShaowDao
import com.eques.demo.R
import com.eques.demo.databinding.ActivityWorkModeBinding
import com.eques.https.ShaowUtils
import com.eques.icvss.utils.ELog
import com.eques.util.BaseAppApplication
import com.eques.util.Config
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONException
import org.json.JSONObject

class WorkModeActivity : BaseActivity() {
    private lateinit var binding: ActivityWorkModeBinding
    private lateinit var shaowDao: ShaowDao
    private var devId: String = ""
    private lateinit var userName: String
    private var isMonitorEnabled = true
    private var timeRange = "全天（00:00-23:59）"
    private var startTime="00:00"
    private var endTime="23:59"

    private var workMode=0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWorkModeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        devId = intent.getStringExtra("devId").toString()
        userName = preference.getString(Config.EQUES_USER_NAME)!!
        initData()
        initView()
    }

    override fun initView() {
        setupViews()
        setupClickListeners()
    }

    override fun initData() {
        initDevShaowInfo()
    }
    private fun initDevShaowInfo() {
        shaowDao = BaseAppApplication.instance!!.getShaowDao(this)
        CoroutineScope(Dispatchers.IO).launch {
            val shaowList = shaowDao.getShaowEntry(userName, devId)
            ELog.e("设备影子详细信息", shaowList)
            if (shaowList != null) {
                workMode=shaowList.work_mode.toInt()
                if(workMode==0){
                    binding.monitorSwitch.isChecked=false
                }else{
                    binding.monitorSwitch.isChecked=true
                }
            }
        }
    }

    private fun setupViews() {
        binding.monitorSwitch.isChecked = isMonitorEnabled
        binding.tvTimeRange.text = timeRange
        updateUIState()
    }

    private fun setupClickListeners() {
        binding.monitorSwitch.setOnCheckedChangeListener { _, isChecked ->
            isMonitorEnabled = isChecked
            if(isChecked){
                workMode=1
            }else{
                workMode=0
            }
            updateUIState()
        }

        binding.monitorTimeLayout.setOnClickListener {
            showTimeRangeDialog()
        }

        binding.btnCancel.setOnClickListener {
            finish()
        }

        binding.btnConfirm.setOnClickListener {
            saveSettings()
        }
    }

    private fun updateUIState() {
        val isEnabled = binding.monitorSwitch.isChecked
        binding.monitorTimeLayout.isEnabled = isEnabled

        val textColor = if (isEnabled) {
            0xFF000000.toInt()
        } else {
            0xFF999999.toInt()
        }
        binding.tvTimeRange.setTextColor(textColor)
    }

    private fun showTimeRangeDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_time_picker, null)
        val timeRangeGroup = dialogView.findViewById<RadioGroup>(R.id.time_range_group)
        val customTimeLayout = dialogView.findViewById<LinearLayout>(R.id.custom_time_layout)
        val startHourSpinner = dialogView.findViewById<Spinner>(R.id.spinner_start_hour)
        val startMinuteSpinner = dialogView.findViewById<Spinner>(R.id.spinner_start_minute)
        val endHourSpinner = dialogView.findViewById<Spinner>(R.id.spinner_end_hour)
        val endMinuteSpinner = dialogView.findViewById<Spinner>(R.id.spinner_end_minute)

        // 设置小时选项 (0-23)
        val hours = (0..23).map { String.format("%02d", it) }
        val hourAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, hours)
        hourAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        startHourSpinner.adapter = hourAdapter
        endHourSpinner.adapter = hourAdapter

        // 设置分钟选项 (0-59，步长为5分钟)
        val minutes = (0..59).filter { it % 5 == 0 }.map { String.format("%02d", it) }
        val minuteAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, minutes)
        minuteAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        startMinuteSpinner.adapter = minuteAdapter
        endMinuteSpinner.adapter = minuteAdapter

        // 设置默认时间
        startHourSpinner.setSelection(0)   // 00时
        startMinuteSpinner.setSelection(0) // 00分
        endHourSpinner.setSelection(23)    // 23时
        endMinuteSpinner.setSelection(minutes.size - 1) // 55分

        // 设置当前选择
        when (timeRange) {
            "工作时间段（9:00-18:00）" -> timeRangeGroup.check(R.id.rb_work_time)
            "全天（00:00-23:59）" -> timeRangeGroup.check(R.id.rb_all_day)
            else -> {
                if (timeRange.startsWith("自定义")) {
                    timeRangeGroup.check(R.id.rb_custom)
                    customTimeLayout.visibility = LinearLayout.VISIBLE
                    parseCustomTime(timeRange, startHourSpinner, startMinuteSpinner, endHourSpinner, endMinuteSpinner)
                } else {
                    timeRangeGroup.check(R.id.rb_all_day)
                }
            }
        }

        timeRangeGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb_custom -> customTimeLayout.visibility = LinearLayout.VISIBLE
                else -> customTimeLayout.visibility = LinearLayout.GONE
            }
        }

        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .setPositiveButton("确定") { _, _ ->
                handleTimeRangeSelection(
                    timeRangeGroup.checkedRadioButtonId,
                    startHourSpinner,
                    startMinuteSpinner,
                    endHourSpinner,
                    endMinuteSpinner
                )

            }
            .setNegativeButton("取消", null)
            .create()

        dialog.show()
    }

    private fun parseCustomTime(
        timeRange: String,
        startHourSpinner: Spinner,
        startMinuteSpinner: Spinner,
        endHourSpinner: Spinner,
        endMinuteSpinner: Spinner
    ) {
        try {
            val regex = """(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})""".toRegex()
            val matchResult = regex.find(timeRange)
            matchResult?.let {
                val startHour = it.groupValues[1].toInt()
                val startMinute = it.groupValues[2].toInt()
                val endHour = it.groupValues[3].toInt()
                val endMinute = it.groupValues[4].toInt()

                // 设置开始时间
                startHourSpinner.setSelection(startHour)
                val minuteIndex = startMinute / 5 // 因为分钟是5的倍数
                if (minuteIndex < startMinuteSpinner.adapter.count) {
                    startMinuteSpinner.setSelection(minuteIndex)
                }

                // 设置结束时间
                endHourSpinner.setSelection(endHour)
                val endMinuteIndex = endMinute / 5
                if (endMinuteIndex < endMinuteSpinner.adapter.count) {
                    endMinuteSpinner.setSelection(endMinuteIndex)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun handleTimeRangeSelection(
        checkedId: Int,
        startHourSpinner: Spinner,
        startMinuteSpinner: Spinner,
        endHourSpinner: Spinner,
        endMinuteSpinner: Spinner
    ) {
        timeRange = when (checkedId) {
            R.id.rb_work_time ->{
                startTime = "09:00"
                endTime = "18:00"
                "工作时间段（9:00-18:00）"
            }
            R.id.rb_all_day ->{
                startTime = "00:00"
                endTime = "23:59"
                "全天（00:00-23:59）"
            }
            R.id.rb_custom -> {
                val startHour = startHourSpinner.selectedItem.toString().toInt()
                val startMinute = startMinuteSpinner.selectedItem.toString().toInt()
                val endHour = endHourSpinner.selectedItem.toString().toInt()
                val endMinute = endMinuteSpinner.selectedItem.toString().toInt()
                startTime = "${String.format("%02d", startHour)}:${String.format("%02d", startMinute)}"
                endTime = "${String.format("%02d", endHour)}:${String.format("%02d", endMinute)}）"
                // 显示选择的时间
                showSelectedTime(startHour, startMinute, endHour, endMinute)

                // 更新显示的时间范围
                "自定义（${String.format("%02d", startHour)}:${String.format("%02d", startMinute)}-${String.format("%02d", endHour)}:${String.format("%02d", endMinute)}）"
            }
            else -> timeRange
        }
        binding.tvTimeRange.text = timeRange

    }

    private fun updateShaowInfo(){
        CoroutineScope(Dispatchers.IO).launch {
            Log.e("更新影子设置数据", "开始")
            //VL2 影子设置
            val jsonObject = JSONObject()
            try {
                jsonObject.put("work_mode", java.lang.String.valueOf(workMode))
                jsonObject.put("alive_start_time", startTime)
                jsonObject.put("alive_stop_time", endTime)
            } catch (e: JSONException) {
                Log.e("更新影子设置数据", e.message!!)
                e.printStackTrace()
            }
            Log.e("更新影子设置数据", jsonObject.toString())
            ShaowUtils.getInstance(context = this@WorkModeActivity).updateSetting(devId, jsonObject)
        }
    }

    private fun showSelectedTime(startHour: Int, startMinute: Int, endHour: Int, endMinute: Int) {
        val message = "开始时间: ${String.format("%02d", startHour)}:${String.format("%02d", startMinute)}\n" +
                "结束时间: ${String.format("%02d", endHour)}:${String.format("%02d", endMinute)}"

        Toast.makeText(this, message, Toast.LENGTH_LONG).show()

        // 也可以使用AlertDialog显示更详细的信息
        AlertDialog.Builder(this)
            .setTitle("选择的时间段")
            .setMessage(message)
            .setPositiveButton("确定", null)
            .show()
    }

    private fun saveSettings() {
        // 保存设置逻辑
        val settings = mapOf(
            "monitor_enabled" to isMonitorEnabled,
            "time_range" to timeRange
        )

        Toast.makeText(this, "监控模式设置已保存：$timeRange", Toast.LENGTH_SHORT).show()

        // 这里可以添加保存到SharedPreferences或服务器的逻辑
        // saveToPreferences(settings)
        updateShaowInfo()
        finish()
    }

    // 保存到SharedPreferences的示例方法
    private fun saveToPreferences(settings: Map<String, Any>) {
        val sharedPreferences = getSharedPreferences("monitor_settings", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putBoolean("monitor_enabled", settings["monitor_enabled"] as Boolean)
        editor.putString("time_range", settings["time_range"] as String)
        editor.apply()
    }
}